package com.sinodata.bsm.cicp.finder.cics;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.common.RegexMatchShellCollector;
import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * CICS区域监控
 * CICSRegionFinder.java
 * <p>
 * 程序返回：区域全名，区域子名，CMF目录
 *
 * @author wangpeng
 */
public class CICSRegionFinder extends CICSFinder {
    private static final Logger logger = Logger.getLogger(RegexMatchShellCollector.class);

    @Override
    public List<String[]> find(String ip, Map params) {
        String hostname = getHostName(ip);
        String shell = "region_name.sh";
        String regex = "\"(\\S+[\\s*\\S*]*)\"";
        Pattern pattern = Pattern.compile(regex);
        List<String[]> reses = new ArrayList<String[]>();
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, shell, 0, 0);
            String strLine = null;
            while ((strLine = reader.readLine()) != null && !strLine.equals("Please type the region name")) {
                Matcher matcher = pattern.matcher(strLine);
                String fullName = "";
                String subName = "";
                String path = "";
                if (matcher.find()) {
                    /*
                     * 每一个String[]表示一个资源数据，String[]数据定义如下：
                     * 第一个元素：资源的内部标示
                     * 第二个元素：资源名称
                     * 第三个元素：资源描述
                     * 第四-第N个参数：返回的属性值
                     */
                    String[] res = new String[6];
                    reses.add(res);
                    fullName = matcher.group(1).trim();
                    String[] subNames = fullName.split("\\.");
                    if (subNames != null && subNames.length > 1) {
                        subName = subNames[1];
                    }
                    path = "/var/cics_regions/" + subName + "/data/CMF.dat";
                    res[0] = hostname + "_" + fullName;
                    res[1] = fullName;
                    res[2] = fullName + " for " + hostname;
                    res[3] = fullName; //区域全名
                    res[4] = subName; //区域子名
                    res[5] = path; //CMF路径
                }
            }
            return reses;
        } catch (IOException e) {
            logger.error("failed to collect by CICSRegion", e);
            e.printStackTrace();
            return null;
        }
    }

}
